<template>
  <div class="search">
    <van-icon name="chat-o" size="30" class="wechat" />
    <van-search v-model="value" placeholder="请输入搜索关键词" class="search-input" />
    <van-icon name="cart-o" size="30" class="wechat" />
  </div>

  <van-tree-select
    v-model:active-id="activeId"
    v-model:main-active-index="activeIndex"
    :items="items"
    @click-nav="handleClickNav"
    @click-item="handleClickItem"
  >
    <!-- 自定义右侧内容 -->
    <template #content>
      <div class="main-scroll">
        <van-grid :column-num="3" :border="false">
          <van-grid-item
            :icon="item.image"
            :text="item.text"
            v-for="(item, index) in currentGridItems"
            :key="index"
            @click="gotoSearchList(item.text)"
          />
        </van-grid>

        <van-tabs
          v-model:active="activeTab"
          v-if="currentGridItems.length > 0"
          @click-tab="handleClickTab"
          @change="handleChange"
          sticky
          offset-top="55px"
        >
          <van-tab :title="tab.title" v-for="(tab, index) in tabs" :key="index">
            <van-list
              v-model:loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              :immediate-check="false"
              @load="onLoad"
              class="goods-list"
            >
              <ul class="like">
                <li v-for="list in mainList" :key="list.iid" class="like-item">
                  <div class="cover">
                    <img :src="list.img" alt="" />
                    <div class="sale gradient-box">已售{{ list.sale }}件</div>
                  </div>
                  <div class="title">{{ list.title }}</div>
                  <div class="price-collect">
                    <div class="price">￥{{ list.price }}</div>
                    <div class="collect">
                      {{ list.cfav }}
                      <van-icon name="star-o" />
                    </div>
                  </div>
                </li>
              </ul>
            </van-list>
          </van-tab>
        </van-tabs>
      </div>
    </template>
  </van-tree-select>
</template>

<script setup>
import { getMainCategory, getSubCategory, getCategoryGoodsList } from '@/api/index.js'
import router from '@/router'

import { ref, onMounted, computed } from 'vue'

const MainCategory = ref([])

const activeId = ref('570217')

const activeIndex = ref(0)

const items = ref([])

const MainCategoryId = computed(() => items.value[activeIndex.value].id)
const page = ref(1)

const currentGridItems = computed(() => {
  return items.value[activeIndex.value]?.children || []
})

const activeTab = ref(0)

const tabs = ref([
  {
    title: '综合',
    value: 'pop',
  },
  {
    title: '销量',
    value: 'sell',
  },
  {
    title: '新品',
    value: 'new',
  },
])

const loading = ref(false)
const finished = ref(false)

const mainList = ref([])

onMounted(async () => {
  // 加载商品主分类
  const mainRes = await getMainCategory()
  MainCategory.value = mainRes.data?.['117330']?.list || []

  // 一级导航
  items.value = MainCategory.value.map((item) => ({
    text: item.title,
    id: item.maitKey,
    children: [],
  }))

  // 并行加载所有子分类
  const subPromises = items.value.map((item) => getSubCategory(item.id))
  const subResults = await Promise.all(subPromises)

  // 正确更新响应式数据
  items.value = items.value.map((item, index) => {
    const list = subResults[index]?.data?.list || []
    return {
      ...item,
      children: list.map((subItem) => ({
        text: subItem.title,
        id: subItem._system_record_entry_id,
        image: subItem.image,
      })),
    }
  })

  // 默认加载综合数据
  loading.value = true

  const list = await getCategoryGoodsList(
    MainCategoryId.value,
    page.value,
    tabs.value[activeTab.value].value,
  )
  mainList.value = list.result.wall.docs
  loading.value = false

  // console.log("items", items.value);
})

const onLoad = async () => {
  page.value++
  loading.value = true
  const list = await getCategoryGoodsList(
    MainCategoryId.value,
    page.value,
    tabs.value[activeTab.value].value,
  )
  if (list.success === 'success') {
    mainList.value.push(...list.result.wall.docs)
    loading.value = false
  } else {
    loading.value = false
    finished.value = true
  }
}

const handleClickTab = () => {}

const handleChange = async () => {
  // console.log("执行了", name);
  mainList.value = []
  page.value = 1
  loading.value = true
  const list = await getCategoryGoodsList(
    MainCategoryId.value,
    page.value,
    tabs.value[activeTab.value].value,
  )
  mainList.value = list.result.wall.docs
  loading.value = false
}

const handleClickNav = async (index) => {
  console.log('主分类索引值', index)
  activeIndex.value = index
  console.log('MainCategoryId', MainCategoryId.value)

  activeTab.value = 0

  mainList.value = []
  page.value = 1
  loading.value = true
  const list = await getCategoryGoodsList(
    MainCategoryId.value,
    page.value,
    tabs.value[activeTab.value].value,
  )
  mainList.value = list.result.wall.docs
  loading.value = false
}

const handleClickItem = (item) => {
  console.log('右侧项目', item)
}

const gotoSearchList = (keyword) => {
  router.push({ path: '/searchList', query: { q: keyword } })
}
</script>

<style lang="scss" scoped>
.main-scroll {
  flex: 1;
  overflow-y: auto;
}

.van-tree-select {
  // 确保容器高度占满屏幕
  height: 100vh !important;

  // 深度选择器穿透组件作用域
  ::v-deep(.van-tree-select__content) {
    // 隐藏所有浏览器滚动条
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE/Edge */

    /* WebKit 内核浏览器 */
    &::-webkit-scrollbar {
      display: none;
    }

    // 核心滚动配置
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; // 启用 iOS 惯性滚动

    // 移动端渲染优化
    transform: translateZ(0);
    backface-visibility: hidden;
    perspective: 1000px;
  }
}

.van-tree-select__content {
  height: calc(100vh - 55px);
  overflow: hidden;
}

:deep(.van-tabs__wrap) {
  // 强制设置定位层级
  position: sticky !important;
  top: 55px !important; // 匹配搜索栏高度
  z-index: 1000;
  background: white;
}

:deep(.van-tabs__wrap--sticky) {
  position: sticky;
  top: 0;
  z-index: 999;
}

:deep(.van-icon__image) {
  width: 100%;
  height: 100%;
}

.search {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 100%;
  background-color: #fff;
  overflow: hidden;
  padding: 0 10px;
  border-top: 1px solid #eee;

  .search-input {
    width: 100%;
  }

  .wechat {
    margin-left: auto;
  }
}

.like {
  list-style: none;
  column-count: 2;
  column-gap: 10px;
  box-sizing: border-box;
  padding: 5px;

  .like-item {
    background-color: #fff;
    border-radius: 5px;
    margin-bottom: 10px;
    break-inside: avoid;
    display: inline-block;
    width: 100%;
    box-sizing: border-box;
    overflow: hidden;
    position: relative;

    .cover {
      position: relative;
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-top-left-radius: 5px;
        border-top-right-radius: 5px;
      }
    }

    .sale {
      position: absolute;
      left: 0;
      text-align: center;
      bottom: 10px;
      color: #fff;
      font-size: 12px;
      padding: 2px 5px;
    }

    .gradient-box {
      background-image: linear-gradient(to right, #6f6262, transparent);
      /* 设置从左到右的线性渐变 */
    }

    .title {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      width: 100%;
      overflow: hidden;
      font-size: 13px;
      padding: 0 5px;
      text-align: center;
      box-sizing: border-box;
    }

    .price-collect {
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: 0 5px;
      overflow: hidden;
    }

    .buy {
      width: auto;
      margin: 0 5px;
      box-sizing: border-box;
      overflow: hidden;
      display: block;
    }
  }
}

:deep(.van-sidebar) {
  width: 50px !important;
}
</style>
